package cn.signalpha.modules.auth.granter;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.signalpha.core.log.exception.ServiceException;
import cn.signalpha.core.tool.utils.StringUtil;
import cn.signalpha.core.tool.utils.WebUtil;
import cn.signalpha.modules.auth.dto.UserInfo;
import cn.signalpha.modules.auth.provider.ITokenGranter;
import cn.signalpha.modules.auth.provider.TokenParameter;
import cn.signalpha.modules.com.entity.UserOauth;
import cn.signalpha.modules.com.entity.enums.UserSourceEnum;
import cn.signalpha.modules.com.service.UserService;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * MobileTokenGranter
 */
@Component
@AllArgsConstructor
public class MiniAppTokenGranter implements ITokenGranter {

	public static final String GRANT_TYPE = "miniapp";

	private final UserService userService;
	private final WxMaService wxMaService;

	@Override
	public UserInfo grant(TokenParameter tokenParameter) {
		HttpServletRequest request = WebUtil.getRequest();

		String code = request.getParameter("code");
		if(StringUtil.isBlank(code)) {
			throw new ServiceException("code不能为空");
		}

		UserOauth userOauth = new UserOauth();
		userOauth.setAppId(wxMaService.getWxMaConfig().getAppid());
		userOauth.setSource(UserSourceEnum.WECHAT_MINI_APP.getValue());
		try {
			WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
			userOauth.setOpenId(session.getOpenid());
			userOauth.setUnionId(session.getUnionid());
		} catch (WxErrorException e) {
			throw new ServiceException(e.getError().getErrorMsg());
		}
		return userService.userInfo(userOauth);
	}

}
